﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>
    <link href="/Styles/Site.css" rel="stylesheet" type="text/css" />
    <title>Get Transit Data using jQuery</title>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
</head>  

<body>  

<button id="btnExecute">Execute</button>
<div id="results"></div>
<div id="message"></div>

<script type="text/javascript">

    var basicUrl = "http://transit.cloudapp.net/TransitOdataService.svc";

    function makeUrl(relativeUrl) {
        var url = relativeUrl;
        var hasQueryParameters = relativeUrl.indexOf('?') >= 0;
        url += hasQueryParameters ? '&' : '?';
        url += "$format=json&$callback=?&api_key=M8xudPElsU2Gwe87MzYKVg";
        return url;
    }

    function getTransitJson(relativeUrl, success) {
        $.getJSON(makeUrl(relativeUrl), function processResult(msg) {
            var results = (msg.d.results || msg.d); // Handle OData Version2 and Version1.
            success(results || msg);
        });
    }

    function isPrimitiveTypeValue(value) {
        return typeof(value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean';
    }

    function displayResults(msg, caption) {
        $('#results').append('<h3>' + caption + '</h3>');
        
        var isSingleValue = !msg.length;
        if (isSingleValue) {
            msg = [msg];
        }

        var html = '<table cellspacing="0">';
        var isHeaderRendered;

        for (var i = 0; i < msg.length; i++) {

            if (!isHeaderRendered) {
                isHeaderRendered = true;
                html += '<tr class="header">';
                for (var p in msg[i]) {
                    var value = msg[i][p];
                    if (!value || isPrimitiveTypeValue(value)) {
                        html += '<td>' + p + '</td>';
                    }
                }
                html += '</tr>';
            }

            html += '<tr>';
            for (var p in msg[i]) {
                var value = msg[i][p];
                if (!value || isPrimitiveTypeValue(value)) {
                    html += "<td nowrap='nowrap'>" + (value || '')  + '</td>';
                }
            }
            html += '</tr>';
        }

        html += '</table>';
        $('#results').append(html);
    }

    function writeTitle(title) {
        $('#results').append('<h3>' + title + '</h3>');
    }

    function clearView() {
        $('#results').html('');
        $('#message').html('Waiting for reply...');
    }

    $(document).ready(function () {
        $('#btnExecute').click(function (evt) {
            evt.preventDefault();

            clearView();
            getAgencies();
        });
    });

    ///////////////////////////////////////////////

    function getAgencies() {
        var url = basicUrl + "/Agencies";
        writeTitle(url);
        getTransitJson(url, onAgenciesReceived);
    }

    function onAgenciesReceived(data) {
        displayResults(data, 'Agencies:');

        var url = basicUrl + "/Agencies('WMATA')";
        writeTitle(url);
        getTransitJson(url, onAgencyReceived);
    }

    function onAgencyReceived(data) {
        displayResults(data, 'Agency:');

        var url = data.Routes.__deferred.uri + "?$skip=10&$top=5&$orderby=RouteType,RouteName";
        writeTitle(url);
        getTransitJson(url, onRoutesReceived);
    }

    function onRoutesReceived(data) {
        displayResults(data, 'WMATA Routes:');

        var url = basicUrl + "/CalculateItineraryByStops?stop1Id='11868'&stop2Id='11882'&startTime=datetime'2009-12-26T01:23:38Z'&$top=1&$expand=Legs";
        writeTitle(url);
        getTransitJson(url, onItinerariesReceived);
    }

    function onItinerariesReceived(data) {
        displayResults(data, 'Itinerary:');
        writeTitle("(msg.d.results || msg.d)[0].Legs.results");
        displayResults(data[0].Legs.results, 'Legs:');

        var url = basicUrl + "/GeoAreas('38.996796|-76.904472|0.05')?$expand=Stops";
        writeTitle(url);
        getTransitJson(url, onAreasReceived);
    }

    function onAreasReceived(data) {
        displayResults(data, 'Area:');
        writeTitle("(msg.d.results || msg.d)[0].Stops.results");
        displayResults(data.Stops.results, 'Area Stops:');

        // Do not forget to encode URLs.
        var url = basicUrl + "/GeoAreas('38.996796|-76.904472|0.05')/Stops?$filter=substringof('EDMINSTON',Name) and substringof('GREENBELT',Name)";
        writeTitle(url);
        getTransitJson(url, onStopReceived);
    }

    function onStopReceived(data) {
        displayResults(data, 'Stop By Name part:');

        $('#message').html('Done.');
    }

</script>  
    
</body>  
</html>  